package com.cxria.shiro.service.impl;

import com.cxria.shiro.dto.PageDto;
import com.cxria.shiro.entity.Permission;
import com.cxria.shiro.entity.Role;
import com.cxria.shiro.entity.RolePermission;
import com.cxria.shiro.repository.RolePermissionRepository;
import com.cxria.shiro.repository.RoleRepository;
import com.cxria.shiro.service.ShiroRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

@Service
public class ShiroRoleServiceImpl implements ShiroRoleService {

	@Autowired
	private RoleRepository roleRepository;

	@Autowired
	private RolePermissionRepository rolePermissionRepository;

	@Override
	@Transactional
	public void save(Role role) {
		List<Permission> permissions = role.getPermissions();
		roleRepository.save(role);
		rolePermissionRepository.deleteByRoleId(role.getId());
		for(Permission permission : permissions){
			RolePermission rolePermission = new RolePermission(role, permission);
			rolePermissionRepository.save(rolePermission);
		}
	}

	@Override
	public Role getByRoleName(String roleName) {
		return roleRepository.findByRoleName(roleName);
	}

	@Override
	public Role getById(long id) {
		return roleRepository.findOne(id);
	}

	@Override
	public List<Role> getAll() {
		return roleRepository.findAll();
	}

	@Override
	public Page<Role> getByPage(PageDto<Role> pageDto) {
		Pageable page = new PageRequest(pageDto.getPageNo(), pageDto.getPageSize());
		return roleRepository.findAll(page);
	}

	@Override
	@Transactional
	public void delete(Long roleId){
		roleRepository.delete(roleId);
		rolePermissionRepository.deleteByRoleId(roleId);
	}

}
